package com.zzw.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.zzw.exception.CommonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
public class JsonHelper {

    private static final Logger logger = LoggerFactory.getLogger(JsonHelper.class);

    private JsonHelper() {
    }

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static String toJson(Object obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("json 序列化错误", e);
            throw new CommonException("-1", "json 序列化错误");
        }
    }

    public static <T> T readValue(String json, Class<T> clazz) {
        try {
            return MAPPER.readValue(json, clazz);
        } catch (IOException e) {
            logger.error("json 反序列化错误", e);
            throw new CommonException("-1", "json 反序列化错误，请检查参数是否合法");
        }
    }

    public static <T> List<T> stringToList(String json, Class<T> object) {
        CollectionType listType = MAPPER.getTypeFactory().constructCollectionType(ArrayList.class, object);
        try {
            return MAPPER.readValue(json, listType);
        } catch (IOException e) {
            logger.error("json 反序列化错误", e);
            throw new CommonException("-1", "json 序列化list错误");
        }
    }

}
